﻿using System.Collections.Concurrent;
using System.Linq;
using Rebazza.Server.Interfaces;

namespace Rebazza.Server.Entities
{
    public class RoomedGameServer : BaseGameServer
    {
        private readonly object thisLock = new object();
        private readonly ConcurrentDictionary<BaseGameRoom, string> rooms; 

        public RoomedGameServer(int gamePort, int roomCount, int minUserCount, int maxUserCount) : base(gamePort)
        {
            rooms = new ConcurrentDictionary<BaseGameRoom, string>();
            for (int i = 0; i < roomCount; i++)
            {
                rooms.TryAdd(new BaseGameRoom(minUserCount, maxUserCount, i), string.Empty);
            }
        }

        //public bool TryCreateRoom(int roomNumber, int minUserCount, int maxUserCount)
        //{
        //    lock (thisLock)
        //    {
        //        if (rooms.Keys.Any(x => x.RoomNumber == roomNumber && !x.IsEmpty))
        //        {
        //            return false;
        //        }

        //        var room = rooms.Keys.Single(x => x.RoomNumber == roomNumber);
        //        room.FillRoom(minUserCount, maxUserCount, roomNumber);
        //        return true;
        //    }
        //}

        public bool TryEnterRoom(int roomNumber, IBaseUser user)
        {
            lock (thisLock)
            {
                var room = rooms.Keys.SingleOrDefault(x => x.RoomNumber == roomNumber);
                if (room != null)
                {
                    return room.TryAddUser(user);
                }

                return false;
            }
        }

        public bool TryExitRoom(int roomNumber, BaseUser user)
        {
            lock (thisLock)
            {
                var room = rooms.Keys.SingleOrDefault(x => x.RoomNumber == roomNumber);
                if (room != null)
                {
                    return room.TryRemoveUser(user);
                }

                return false;
            }
        }

        //public int TryCreateRandomRoom(int minUserCount, int maxUserCount)
        //{
        //    var random = new Random();
        //    if (emptyRooms.Count > 0)
        //    {
        //        int index = random.Next(0, emptyRooms.Count - 1);
        //        var room = new BaseGameRoom(minUserCount, maxUserCount, emptyRooms.Keys.);
        //        existingRooms.TryAdd()
        //    }
        //}
    }
}
